import {useNavigate, useParams} from "react-router-dom";
import {Avatar, Button, Card, message, Popconfirm} from "antd";
import {useEffect, useState} from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {
    ArrowLeftOutlined,
    CalendarOutlined,
    DeleteOutlined,
    EditOutlined,
    HistoryOutlined,
    KeyOutlined,
    ManOutlined,
    UserAddOutlined,
    UserOutlined
} from "@ant-design/icons";
import UserBasicEdit from "../../../components/console/user/userBasicEdit";
import UserIntroEdit from "../../../components/console/user/userIntroEdit";
import UserRoleAllocate from "../../../components/console/permission/UserRoleAllocate";

/**
 * 用户管理详情页面
 * @constructor
 */
const ConsoleUserDetail = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 操作类型, 用户id 从当前路由地址中获取
    const {operation, userId} = useParams();

    // 编辑用户信息模态框状态
    const [editUserModalVisible, setEditUserModalVisible] = useState({
        basicEdit: false, // 编辑基础信息
        introductionEdit: false, // 编辑个人介绍
        allocateUserRole: false, // 为用户分配角色
    })

    // 页面上展示的用户详情
    const [userDetail, setUserDetail] = useState({
        userAccount: "",
        userNickname: "",
        userGender: "",
        userGenderValue: "",
        userIntroduction: "",
        relationRoleDtos: [],
        relationPermissions: [],
        createdTime: null,
        createdByUserNickname: "",
        lastModifiedTime: null,
        lastModifiedByUserNickname: "",
    });

    // 编辑用户信息时的填写数据
    const [editUserParam, setEditUserParam] = useState({
        userNickname: "",
        userGender: "",
        userGenderValue: "",
        userIntroduction: ""
    })

    /**
     * 跳转回用户管理页面
     */
    const back2ConsoleUserPage = () => {
        navigate("/console/user");
    }

    /**
     * 根据id查询用户信息
     */
    const searchUserById = () => {
        RequestUtils.post(RequestApis.userManage.searchById, {
            id: userId
        }).then(res => {
            setUserDetail(res.data.data);
        }).catch(err => {
            messageApi.error(err.message).then(
                () => {
                    back2ConsoleUserPage();
                }
            );
        })
    }

    /**
     * 根据id编辑用户
     */
    const editUserById = (editUserParam) => {
        RequestUtils.post(RequestApis.userManage.editById, {
            id: userId,
            userNickname: editUserParam.userNickname,
            userGender: editUserParam.userGender,
            userIntroduction: editUserParam.userIntroduction
        }).then(() => {
            searchUserById(userId);
            messageApi.success("编辑用户信息成功");
        }).catch(err => {
            messageApi.error(err.message);
        })
    }

    /**
     * 根据id删除用户
     */
    const removeUserById = () => {
        RequestUtils.post(RequestApis.userManage.removeById, {
            id: userId
        }).then(() => {
            messageApi.success("删除用户信息成功，即将跳转到用户管理页面").then(() => {
                back2ConsoleUserPage();
            })
        }).catch(err => {
            messageApi.error(err.message);
        })
    }

    /**
     * 打开页面时直接查询用户详情
     */
    useEffect(() => {
        searchUserById();
        // eslint-disable-next-line
    }, []);

    return (
        <div style={{
            padding: '24px'
        }}>
            {contextHolder}

            {/* 返回按钮 - 增强过渡效果 */}
            <div style={{
                marginBottom: '24px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between'
            }}>
                <div>
                    <Button
                        type="primary"
                        onClick={back2ConsoleUserPage}
                        style={{
                            borderRadius: '20px',
                            padding: '6px 20px',
                            backgroundColor: '#1890ff',
                            borderColor: '#1890ff',
                            transition: 'all 0.3s ease',
                            transform: 'translateY(0)',
                            boxShadow: '0 2px 8px rgba(24, 144, 255, 0.2)',
                            width: '340px'
                        }}
                        hoverStyle={{
                            backgroundColor: '#096dd9',
                            transform: 'translateY(-3px)',
                            boxShadow: '0 4px 16px rgba(24, 144, 255, 0.3)',
                            borderColor: '#096dd9'
                        }}
                    >
                        <ArrowLeftOutlined style={{marginRight: '6px'}}/>
                        返回用户管理页面
                    </Button>
                </div>

                {operation === "edit" ?
                    <div>
                        <Popconfirm
                            style={{width: '400px'}}
                            placement="leftTop"
                            title={"删除用户操作确认"}
                            description={"确定要删除当前用户？ 删除后数据将无法恢复。"}
                            okText="确认删除"
                            cancelText="取消"
                            onConfirm={() => {
                                removeUserById();
                            }}
                        >
                            <Button
                                type="primary"
                                style={{
                                    borderRadius: '20px',
                                    padding: '6px 20px',
                                    backgroundColor: '#ff6666',
                                    borderColor: '#ff6666',
                                    transition: 'all 0.3s ease',
                                    transform: 'translateY(0)',
                                    boxShadow: '0 2px 8px rgba(24, 144, 255, 0.2)',
                                    width: '340px'
                                }}
                                hoverStyle={{
                                    backgroundColor: '#ff6666',
                                    transform: 'translateY(-3px)',
                                    boxShadow: '0 4px 16px rgba(24, 144, 255, 0.3)',
                                    borderColor: '#ff6666'
                                }}
                            >
                                <DeleteOutlined style={{marginRight: '6px'}}/>
                                删除当前用户
                            </Button>
                        </Popconfirm>
                    </div> :
                    <div/>}

            </div>

            {/* 主要内容区 */}
            <div style={{
                display: 'flex',
                gap: '24px',
                flexWrap: 'wrap',
                justifyContent: 'center'
            }}>

                {/* 左侧用户信息卡片 - 新增卡片hover上浮+阴影效果 */}
                <div style={{width: '40%'}}>
                    <Card style={{
                        borderRadius: '16px',
                        overflow: 'hidden',
                        border: '1px solid #e0e0e0', // 增强边框
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                        backgroundColor: '#fff',
                        transition: 'all 0.3s ease',
                        transform: 'translateY(0)'
                    }}
                          hoverStyle={{
                              transform: 'translateY(-5px)',
                              boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08)',
                              borderColor: '#d0d0d0' //  hover时加深边框
                          }}
                    >
                        {/* 卡片头部背景 - 新增渐变动画（改用event.target） */}
                        <div style={{
                            height: '80px',
                            backgroundColor: 'linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%)',
                            marginBottom: '-40px',
                            transition: 'background-position 0.8s ease',
                            backgroundSize: '200% 200%',
                            backgroundPosition: '0% 50%'
                        }}
                             onMouseEnter={(e) => {
                                 e.target.style.backgroundPosition = '100% 50%';
                             }}
                             onMouseLeave={(e) => {
                                 e.target.style.backgroundPosition = '0% 50%';
                             }}
                        />

                        {/* 头像 - 新增hover旋转+缩放效果（改用event.target） */}
                        <div style={{
                            display: 'flex',
                            justifyContent: 'center',
                            marginBottom: '16px'
                        }}>
                            <Avatar
                                size={88}
                                icon={<UserOutlined style={{fontSize: '40px'}}/>}
                                style={{
                                    border: '4px solid white',
                                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                                    backgroundColor: '#4cc9f0',
                                    transition: 'all 0.3s ease',
                                    transform: 'rotate(0) scale(1)'
                                }}
                                onMouseEnter={(e) => {
                                    e.target.style.transform = 'rotate(5deg) scale(1.05)';
                                    e.target.style.boxShadow = '0 4px 12px rgba(76, 201, 240, 0.3)';
                                }}
                                onMouseLeave={(e) => {
                                    e.target.style.transform = 'rotate(0) scale(1)';
                                    e.target.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
                                }}
                            />
                        </div>

                        {/* 用户昵称 - 新增hover文字发光效果（改用event.target） */}
                        <div style={{
                            display: 'flex',
                            justifyContent: 'center',
                            marginTop: '12px'
                        }}>
                            <span style={{
                                fontSize: '20px',
                                fontWeight: 600,
                                color: '#333',
                                transition: 'all 0.3s ease',
                                textShadow: '0 0 0 rgba(0,0,0,0)'
                            }}
                                  onMouseEnter={(e) => {
                                      e.target.style.textShadow = '0 0 8px rgba(24, 144, 255, 0.2)';
                                      e.target.style.color = '#1890ff';
                                  }}
                                  onMouseLeave={(e) => {
                                      e.target.style.textShadow = '0 0 0 rgba(0,0,0,0)';
                                      e.target.style.color = '#333';
                                  }}
                            >
                                {userDetail.userNickname || '未设置昵称'}
                            </span>
                        </div>

                        {/* 个人介绍 */}
                        {operation === 'edit' ?
                            <div style={{
                                display: 'flex',
                                justifyContent: 'end',
                                marginRight: '24px',
                                marginTop: '10px'
                            }}>
                                <span
                                    style={{color: '#3333ff', cursor: ' pointer'}}
                                    onClick={() => {
                                        setEditUserModalVisible({
                                            introductionEdit: true
                                        });
                                    }}
                                >
                                    <EditOutlined style={{marginRight: '6px'}}/>
                                    <span style={{borderBottom: '1px solid #3333ff'}}>编辑个人介绍</span>
                                </span>
                            </div> :
                            <div style={{marginTop: '20px'}}/>
                        }

                        <div style={{
                            padding: '16px',
                            marginTop: '20px',
                            backgroundColor: '#f8f9fa',
                            borderRadius: '12px',
                            margin: '0 16px',
                            transition: 'background-color 0.3s ease'
                        }}
                             onMouseEnter={(e) => {
                                 e.target.style.backgroundColor = '#f0f2f5';
                             }}
                             onMouseLeave={(e) => {
                                 e.target.style.backgroundColor = '#f8f9fa';
                             }}
                        >
                            <div style={{
                                fontSize: '14px',
                                color: '#666',
                                lineHeight: '1.6',
                                marginTop: '4px'
                            }}>
                                {userDetail.userIntroduction || '这个人很懒，什么也没留下……'}
                            </div>
                        </div>

                        {/* 时间信息 - 新增条目hover高亮（改用event.target） */}
                        <div style={{
                            padding: '16px',
                            display: 'flex',
                            flexDirection: 'column',
                            gap: '8px',
                            marginTop: '12px'
                        }}>
                            {[
                                {icon: <CalendarOutlined/>, label: '创建时间', value: userDetail.createdTime || '未知'},
                                {
                                    icon: <UserAddOutlined/>,
                                    label: '创建人',
                                    value: userDetail.createdByUserNickname || '系统'
                                },
                                {
                                    icon: <HistoryOutlined/>,
                                    label: '最后修改时间',
                                    value: userDetail.lastModifiedTime || '未修改'
                                },
                                {
                                    icon: <EditOutlined/>,
                                    label: '最后修改人',
                                    value: userDetail.lastModifiedByUserNickname || '未知'
                                }
                            ].map((item, index) => (
                                <div key={index} style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    fontSize: '13px',
                                    color: '#666',
                                    padding: '4px 8px',
                                    borderRadius: '8px',
                                    transition: 'all 0.2s ease',
                                    cursor: 'default'
                                }}
                                     onMouseEnter={(e) => {
                                         e.target.style.backgroundColor = '#f0f7ff';
                                         e.target.style.color = '#1890ff';
                                         // 获取当前元素内的svg图标（第一个子元素）
                                         const icon = e.target.querySelector('svg');
                                         if (icon) icon.style.color = '#096dd9';
                                     }}
                                     onMouseLeave={(e) => {
                                         e.target.style.backgroundColor = 'transparent';
                                         e.target.style.color = '#666';
                                         const icon = e.target.querySelector('svg');
                                         if (icon) icon.style.color = '#1890ff';
                                     }}
                                >
                                    <span style={{
                                        marginRight: '8px',
                                        color: '#1890ff'
                                    }}>{item.icon}</span>
                                    {item.label}: {item.value}
                                </div>
                            ))}
                        </div>
                    </Card>
                </div>

                {/* 右侧信息区域 */}
                <div style={{
                    flex: 1,
                    width: '40%'
                }}>
                    {/* 基本信息卡片 */}
                    <Card style={{
                        borderRadius: '16px',
                        border: '1px solid #e0e0e0', // 增强边框
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                        backgroundColor: '#fff',
                        marginBottom: '24px',
                        transition: 'all 0.3s ease',
                        transform: 'translateY(0)'
                    }}
                          hoverStyle={{
                              transform: 'translateY(-3px)',
                              boxShadow: '0 6px 18px rgba(0, 0, 0, 0.07)',
                              borderColor: '#d0d0d0' //  hover时加深边框
                          }}
                    >
                        <div style={{width: '100%', display: 'flex', justifyContent: 'space-between'}}>
                            <div style={{
                                fontSize: '16px',
                                fontWeight: 600,
                                color: '#ff007f',
                                marginBottom: '16px',
                                paddingBottom: '8px',
                                borderBottom: '1px solid #f0f0f0'
                            }}>
                                基本信息
                            </div>

                            {operation === "edit" ?
                                <div>
                                    <Button
                                        color="pink"
                                        variant="solid"
                                        style={{width: '220px'}}
                                        onClick={() => {
                                            setEditUserModalVisible({
                                                ...editUserModalVisible,
                                                basicEdit: true
                                            });
                                        }}
                                    >
                                        编辑基础信息
                                    </Button>
                                </div> :
                                <div/>
                            }
                        </div>


                        <div style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
                            gap: '16px'
                        }}>
                            {/* 账号模块 - 新增hover背景加深 */}
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                padding: '12px',
                                borderRadius: '10px',
                                backgroundColor: '#f0f7ff',
                                transition: 'background-color 0.3s ease',
                                cursor: 'default'
                            }}
                                 onMouseEnter={(e) => {
                                     e.target.style.backgroundColor = '#e6f4ff';
                                 }}
                                 onMouseLeave={(e) => {
                                     e.target.style.backgroundColor = '#f0f7ff';
                                 }}
                            >
                                <KeyOutlined style={{
                                    marginRight: '10px',
                                    color: '#1890ff',
                                    fontSize: '16px'
                                }}/>
                                <div>
                                    <div style={{fontSize: '12px', color: '#666'}}>账号</div>
                                    <div style={{fontSize: '14px', color: '#333', marginTop: '4px'}}>
                                        {userDetail.userAccount || '未知'}
                                    </div>
                                </div>
                            </div>

                            {/* 昵称模块 - 新增hover背景加深 */}
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                padding: '12px',
                                borderRadius: '10px',
                                backgroundColor: '#fff0f0',
                                transition: 'background-color 0.3s ease',
                                cursor: 'default'
                            }}
                                 onMouseEnter={(e) => {
                                     e.target.style.backgroundColor = '#ffe6e6';
                                 }}
                                 onMouseLeave={(e) => {
                                     e.target.style.backgroundColor = '#fff0f0';
                                 }}
                            >
                                <UserOutlined style={{
                                    marginRight: '10px',
                                    color: '#f5222d',
                                    fontSize: '16px'
                                }}/>
                                <div>
                                    <div style={{fontSize: '12px', color: '#666'}}>昵称</div>
                                    <div style={{fontSize: '14px', color: '#333', marginTop: '4px'}}>
                                        {userDetail.userNickname || '未设置'}
                                    </div>
                                </div>
                            </div>

                            {/* 性别模块 - 新增hover背景加深 */}
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                padding: '12px',
                                borderRadius: '10px',
                                backgroundColor: userDetail.userGenderValue ? '#f6ffed' : '#f5f5f5',
                                transition: 'background-color 0.3s ease',
                                cursor: 'default'
                            }}
                                 onMouseEnter={(e) => {
                                     e.target.style.backgroundColor = userDetail.userGenderValue ? '#eaffde' : '#ebebeb';
                                 }}
                                 onMouseLeave={(e) => {
                                     e.target.style.backgroundColor = userDetail.userGenderValue ? '#f6ffed' : '#f5f5f5';
                                 }}
                            >
                                {userDetail.userGenderValue ? (
                                    <ManOutlined style={{
                                        marginRight: '10px',
                                        color: '#52c41a',
                                        fontSize: '16px'
                                    }}/>
                                ) : (
                                    <UserOutlined style={{
                                        marginRight: '10px',
                                        color: '#999',
                                        fontSize: '16px'
                                    }}/>
                                )}
                                <div>
                                    <div style={{fontSize: '12px', color: '#666'}}>性别</div>
                                    <div style={{
                                        fontSize: '14px',
                                        color: userDetail.userGenderValue ? '#333' : '#999',
                                        marginTop: '4px'
                                    }}>
                                        {userDetail.userGenderValue || '未设置'}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Card>

                    {/* 关联角色卡片 */}
                    <Card style={{
                        borderRadius: '16px',
                        border: '1px solid #e0e0e0', // 增强边框
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                        backgroundColor: '#fff',
                        marginBottom: '24px',
                        transition: 'all 0.3s ease',
                        transform: 'translateY(0)'
                    }}
                          hoverStyle={{
                              transform: 'translateY(-3px)',
                              boxShadow: '0 6px 18px rgba(0, 0, 0, 0.07)',
                              borderColor: '#d0d0d0' //  hover时加深边框
                          }}
                    >
                        <div style={{width: '100%', display: 'flex', justifyContent: 'space-between'}}>
                            <div style={{
                                fontSize: '16px',
                                fontWeight: 600,
                                color: '#6600cc',
                                marginBottom: '16px',
                                paddingBottom: '8px',
                                borderBottom: '1px solid #f0f0f0'
                            }}>
                                关联角色
                            </div>
                            {operation === "edit" ?
                                <div>
                                    <Button
                                        color="purple"
                                        variant="solid"
                                        style={{width: '220px'}}
                                        onClick={() => {
                                            setEditUserModalVisible({
                                                ...editUserModalVisible,
                                                allocateUserRole: true
                                            });
                                        }}
                                    >
                                        分配角色
                                    </Button>
                                </div> :
                                <div/>
                            }
                        </div>

                        <div style={{
                            display: 'flex',
                            flexWrap: 'wrap',
                            gap: '12px',
                            padding: '8px 0'
                        }}>
                            {userDetail.relationRoleDtos.length > 0 ? (
                                userDetail.relationRoleDtos.map(item => (
                                    <div
                                        key={item.id}
                                        style={{
                                            border: '1px solid #e6f7ff',
                                            padding: '6px 14px',
                                            borderRadius: '20px',
                                            backgroundColor: '#e6f7ff',
                                            color: '#1890ff',
                                            fontSize: '13px',
                                            transition: 'all 0.2s ease',
                                            whiteSpace: 'nowrap',
                                            cursor: 'default',
                                            transform: 'translateY(0)'
                                        }}
                                        onMouseEnter={(e) => {
                                            e.target.style.transform = 'translateY(-2px)';
                                            e.target.style.boxShadow = '0 4px 12px rgba(24, 144, 255, 0.2)';
                                            e.target.style.backgroundColor = '#d1eaff';
                                        }}
                                        onMouseLeave={(e) => {
                                            e.target.style.transform = 'translateY(0)';
                                            e.target.style.boxShadow = 'none';
                                            e.target.style.backgroundColor = '#e6f7ff';
                                        }}
                                    >
                                        {item.roleName}
                                    </div>
                                ))
                            ) : (
                                <div style={{
                                    color: '#999',
                                    fontSize: '14px',
                                    padding: '12px',
                                    transition: 'color 0.3s ease'
                                }}
                                     onMouseEnter={(e) => {
                                         e.target.style.color = '#666';
                                     }}
                                     onMouseLeave={(e) => {
                                         e.target.style.color = '#999';
                                     }}
                                >
                                    未关联任何角色
                                </div>
                            )}
                        </div>
                    </Card>

                    {/* 用户权限 */}
                    <Card style={{
                        borderRadius: '16px',
                        border: '1px solid #e0e0e0', // 增强边框
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.05)',
                        backgroundColor: '#fff',
                        transition: 'all 0.3s ease',
                        transform: 'translateY(0)'
                    }}
                          hoverStyle={{
                              transform: 'translateY(-3px)',
                              boxShadow: '0 6px 18px rgba(0, 0, 0, 0.07)',
                              borderColor: '#d0d0d0' //  hover时加深边框
                          }}
                    >
                        <div style={{
                            fontSize: '16px',
                            fontWeight: 600,
                            color: '#cc6600',
                            marginBottom: '16px',
                            paddingBottom: '8px',
                            borderBottom: '1px solid #f0f0f0'
                        }}>
                            用户权限
                        </div>
                        <div style={{
                            display: 'flex',
                            flexWrap: 'wrap',
                            gap: '12px',
                            padding: '8px 0'
                        }}>
                            {userDetail.relationPermissions.length > 0 ? (
                                userDetail.relationPermissions.map(item => (
                                    <div
                                        key={item.id}
                                        style={{
                                            border: '1px solid #fff2e8',
                                            padding: '6px 14px',
                                            borderRadius: '20px',
                                            backgroundColor: '#fff2e8',
                                            color: '#fa8c16',
                                            fontSize: '13px',
                                            transition: 'all 0.2s ease',
                                            whiteSpace: 'nowrap',
                                            cursor: 'default',
                                            transform: 'translateY(0)'
                                        }}
                                        onMouseEnter={(e) => {
                                            e.target.style.transform = 'translateY(-2px)';
                                            e.target.style.boxShadow = '0 4px 12px rgba(250, 140, 22, 0.2)';
                                            e.target.style.backgroundColor = '#ffe8cc';
                                        }}
                                        onMouseLeave={(e) => {
                                            e.target.style.transform = 'translateY(0)';
                                            e.target.style.boxShadow = 'none';
                                            e.target.style.backgroundColor = '#fff2e8';
                                        }}
                                    >
                                        {item.permissionName}
                                    </div>
                                ))
                            ) : (
                                <div style={{
                                    color: '#999',
                                    fontSize: '14px',
                                    padding: '12px',
                                    transition: 'color 0.3s ease'
                                }}
                                     onMouseEnter={(e) => {
                                         e.target.style.color = '#666';
                                     }}
                                     onMouseLeave={(e) => {
                                         e.target.style.color = '#999';
                                     }}
                                >
                                    未分配任何权限
                                </div>
                            )}
                        </div>
                    </Card>
                </div>
            </div>

            {/* 编辑基础信息模态框 */}
            <UserBasicEdit
                editUserModalVisible={editUserModalVisible}
                setEditUserModalVisible={setEditUserModalVisible}
                userDetail={userDetail}
                editUserParam={editUserParam}
                setEditUserParam={setEditUserParam}
                editUserById={editUserById}
            />

            {/* 编辑个人介绍模态框 */}
            <UserIntroEdit
                editUserModalVisible={editUserModalVisible}
                setEditUserModalVisible={setEditUserModalVisible}
                userDetail={userDetail}
                editUserParam={editUserParam}
                setEditUserParam={setEditUserParam}
                editUserById={editUserById}
            />

            {/* 为用户分配角色模态框 */}
            <UserRoleAllocate
                editUserModalVisible={editUserModalVisible}
                setEditUserModalVisible={setEditUserModalVisible}
                userId={userId}
                roles={userDetail.relationRoleDtos}
                searchUserById={searchUserById}
            />

        </div>
    )
}

export default ConsoleUserDetail;